package com.ceadeal.admin.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

/**
 * 文件上传
 *
 * @author Westin Yang
 * @date 2017-03-13 21:01:201
 */
@Service
public class FileService {

    private static final Logger log = LoggerFactory.getLogger(FileService.class);

    @Value("${spring.http.multipart.max-file-size}")
    private String MAX_FILE_SIZE;

    /**
     * 功能描述：文件上传
     * @param request
     * @param file 文件
     * @return
     * @throws
     *
     * @author Yzw
     * @date 2016/8/17 0017,9:22
     **/
    public String upload(HttpServletRequest request, MultipartFile file) {
        try {
            //文件保存目录路径
            String savePath = request.getServletContext().getRealPath("/") + "/upload/";
            //文件保存目录URL
            String saveUrl  = request.getContextPath() + "/upload/";

            //定义允许上传的文件扩展名
            HashMap<String, String> extMap = new HashMap<>();
            extMap.put("image", "gif,jpg,jpeg,png,bmp");
            extMap.put("flash", "swf,flv");
            extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            long maxSize = parseSize(MAX_FILE_SIZE);

            String dirName = request.getParameter("dir");
            if (dirName == null) {
                dirName = "image";
            }

            if(!extMap.containsKey(dirName)){
                return getError("目录名不正确。");
            }
            //创建文件夹
            savePath += dirName + "/";
            saveUrl += dirName + "/";
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            Date nowDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String ymd = sdf.format(nowDate);
            savePath += ymd + "/";
            saveUrl += ymd + "/";
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            // 上传
            String fileName = file.getName();
            long fileSize = file.getSize();
            //检查文件大小
            if(fileSize > maxSize){
                return getError("上传文件大小超过限制。");
            }
            //检查扩展名
            String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());

            if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt.toLowerCase())){
                return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "-" + new Random().nextInt(10000) + "." + fileExt;
            try{
                File uploadFile = new File(savePath + newFileName);
                byte[] bytes = file.getBytes();
                FileCopyUtils.copy(bytes, uploadFile);
            }catch(Exception e){
                return getError("上传文件失败。");
            }

            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("result", (saveUrl + newFileName));

            log.info("upload success: " + (saveUrl + newFileName));
            return obj.toJSONString();
        } catch (Exception e) {
            log.info("upload error: " + e.getMessage());
            return getError("上传文件失败。");
        }
    }

    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toString();
    }

    private long parseSize(String size) {
        Assert.hasLength(size, "文件大小不允许为空");
        size = size.toUpperCase();
        return size.endsWith("KB")?Long.valueOf(size.substring(0, size.length() - 2)).longValue() * 1024L:(size.endsWith("MB")?Long.valueOf(size.substring(0, size.length() - 2)).longValue() * 1024L * 1024L:Long.valueOf(size).longValue());
    }

}
